import config from '@/common/config.js'
import i18n from '@/locale/i18n.js'



const $request = (url, data, method = 'GET', headers = {}) => {
	
	return new Promise((resolve, reject) => {
		// uni.showLoading({
		// 	title: '加载中',
		// 	icon: 'loading',
		// 	mask: true
		// });
		
		if(uni.getStorageSync('token')){
			headers = {
				Authorization: uni.getStorageSync('token')
			}
		}
		let tradeService = url.includes("tradeService")
		uni.request({
			url: (tradeService ? 'https://tradeapi.wnabase.com': config.baseURL) + url,
			// url: url,
			method: method,
			data: data,
			header: {
				'Content-Type': "application/json",
				'Accept-Language': i18n.global.locale == 'en' ? 'en' : 'zh',
				...headers
			},
			success(res) {
				if(res.data.status == 401) {
					uni.removeStorageSync('token')
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}, 2000)
					return;
				}else if(res.data.status == 0) {
					resolve(res.data)
				}else {
					uni.$u.toast(res.data.errorMessage)
				}
				// uni.hideLoading(); //关闭loading
			},
			fail(error) {
				reject(error);
				// uni.hideLoading(); //关闭loading
			},
			complete() {
				// uni.hideLoading(); //关闭loading
			}
		})
	})
}
//给uniapp原生的requset赋值
//记得要在mian.js中引用
uni.$request = $request